<?php

$periods = array();

for ($i=2013; $i<date("Y")+2; $i++){
    for ($j=1; $j<13; $j++){
        $periods[] = str_pad($j, 2, "0", STR_PAD_LEFT) . '/' . $i;
    }
}

$GLOBALS['template_data']['periods'] = $periods;
$GLOBALS['template_data']['today'] = date("m/Y");
$GLOBALS['template_data']['show'] = 0;

if (isset($_REQUEST['period']) && !empty ($_REQUEST['period'])){
    $GLOBALS['template_data']['show'] = 1;
    $selectedPeriod = $_REQUEST['period'];
    $selectedPeriodExplode = explode('/', $selectedPeriod);
    $GLOBALS['template_data']['selectedMonthName'] = date("F", mktime(12, 0, 0, $selectedPeriodExplode[0], 2, $selectedPeriodExplode[1]));
    $GLOBALS['template_data']['selectedMonth'] = $selectedPeriodExplode[0];
    $GLOBALS['template_data']['selectedYear'] = $selectedPeriodExplode[1];
    
    $filter = array(
        'monthlyPrepaid >' => 0,
        'active' => 0
    );
    
    $db_obj = new db_obj();
    $client_obj = new client_obj();
    $record_obj = new record_obj();
    
    $clients = $client_obj->getAllClients("*", $filter, 'name ASC');
    
    if (error_obj::isError($clients)){
        error_obj::setError($clients, UNEXCEPTED);
    } else {
        
        foreach ($clients as $key => $value) {
            $filter = array(
                'client' => $value['klient_id'],
                'monthm' => $selectedPeriodExplode[0],
                'year' => $selectedPeriodExplode[1],
                'tariff' => 6
            );
            $records = $record_obj->getListOfRecords($filter);
            
            $expended = 0;
            foreach ($records as $k => $record) {
                $expended += $record['amount'];
            }
            $clients[$key]['expended'] = $expended;
            $clients[$key]['unexpended'] = $value['monthlyPrepaid'] - $expended;
            $clients[$key]['monthlyPrepaid'] = $value['monthlyPrepaid'];
            
            if (empty($clients[$key]['unexpended'])){
                unset($clients[$key]);
            }
            
        }
        
        $GLOBALS['template_data']['clients'] = $clients;
    }
    
}

?>
